from flask import jsonify, request
from flask_login import current_user
from flask.views import MethodView
from app.models.article import Article
from ..auth import auth_required, auth_self_required
from ..forms import ArticleAuditForm
from app.models.attachment import Attachment
from app.forms.article import ArticleForm
from webargs import fields
from webargs.flaskparser import parser
from app.decorators import permission_required
import json
from app.extensions import db


parser_args = {
    'page': fields.Int(missing=0, error_messages={'invalid': '必须是数值类型'}),
    'cid': fields.Int(),
}

search_args = {
    'page': fields.Int(missing=0, error_messages={'invalid': '必须是数值类型'}),
    'text': fields.Str(required=True, error_messages={'required': '查询关键字必须'})
}


class ArticleAPI(MethodView):
    """专报文章
    GET:获取
    POST:修改
    DELETE:删除
    条件：需要授权，并是文章拥有者
    """
    decorators = [auth_self_required, auth_required]

    @permission_required('API_ARTICLE_VIEW')
    def get(self, id):
        model = Article.query.get_or_404(id)
        return jsonify(success=True, data=model.to_dict(content=True))

    @permission_required('API_ARTICLE_UPDATE')
    def post(self, id):
        form = ArticleForm(csrf_enabled=False)
        model = Article.query.get_or_404(id)

        if model.audit_status == 7:
            return jsonify(success=False, message='文章已给审核，不允许操作!')

        if model.save(form):

            for i in json.loads(form.attachment.data):
                attachment = Attachment.query.get_or_404(i)
                model.attachments.append(attachment)
            db.session.commit()

            return jsonify(success=True, data=model.to_dict(content=True))
        if form.errors:
            message = {i[0]: i[1][0] for i in form.errors.items()},
            return jsonify(success=False, message=message)

    @permission_required('API_ARTICLE_DELETE')
    def delete(self, id):
        model = Article.query.get_or_404(id)
        model.delete()
        return jsonify(success=True, message='删除成功!')


class ArticlesAPI(MethodView):
    """专报文章列表获取
    GET:获取文章列表，当用户角色为操作员时，只能获取当前身份下的文章,管理员可获取所有文章.
    POST:创建文章.
    """
    decorators = [auth_required]

    @permission_required('API_ARTICLE_INDEX')
    def get(self):
        """获取当前用户的所有文章
        条件：文章状态为9，用户为当前用户
        """
        args = parser.parse(parser_args, request)
        query = Article.query.filter(Article.status==9).order_by(Article.id.desc())

        if current_user.role.name == 'Audit':
            query = query.filter(Article.audit_status < 9)

        if current_user.role.name == 'User':
            query = query.filter(Article.uid==current_user.id)

        if current_user.role.name == 'Head':
            query = query.filter(Article.uid.in_([u.id for u in current_user.company.users]))

        query = query.filter(Article.cid==args.get('cid')) if args.get('cid') else query
        data = Article.to_collection_dict(query, args['page'], 10)
        return jsonify(success=True, data=data)

    @permission_required('API_ARTICLE_CREATE')
    def post(self):
        form = ArticleForm(csrf_enabled=False)
        model = Article()

        if model.save(form, uid=current_user.id):
            for i in json.loads(form.attachment.data):
                attachment = Attachment.query.get_or_404(i)
                model.attachments.append(attachment)
            db.session.commit()

            return jsonify(success=True, data=model.to_dict())

        if form.errors:
            message = {i[0]: i[1][0] for i in form.errors.items()},
            return jsonify(success=False, message=message)


class ArticleSearchAPI(MethodView):
    decorators = [auth_required]

    @permission_required('API_ARTICLE_SEARCH')
    def get(self):
        args = parser.parse(search_args, request)
        query = Article.query.filter(Article.title.like('%{}%'.format(args.get('text').strip())))
        if current_user.role.name != 'Administrator':
            query = query.filter(Article.user == current_user)
        data = Article.to_collection_dict(query, args['page'], 10)
        return jsonify(success=True, data=data)


class ArticleAuditAPI(MethodView):
    decorators = [auth_required]

    @permission_required('API_ARTICLE_AUDIT')
    def post(self, id):
        form = ArticleAuditForm()

        model = Article.query.get_or_404(id)

        status = [
            ('Head', 10, 9, '一'),
            ('Audit', 8, 7, '二')
        ]

        for tag, *args, text in status:
            if current_user.role.name == 'Audit':
                if model.audit_status > 9:
                    return jsonify(success=False, message='一审未通过。无权操作')

            if current_user.role.name == tag:
                if form.audit_status.data not in args:
                    return jsonify(success=False, message='只能操作{}审'.format(text))

        if model.save(form):
            return jsonify(success=True, data=model.to_dict(content=True))

        if form.errors:
            message = {i[0]: i[1][0] for i in form.errors.items()},
            return jsonify(success=False, message=message)
